package org.jadestudio.dsdown.action;

import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.jadestudio.dsdown.dao.ArticleManageDao;
import org.jadestudio.dsdown.entity.ManageArticle;
import org.jadestudio.dsdown.entity.ManageGamePublishCompany;
import org.jadestudio.dsdown.service.ArticleManageService;
import org.jadestudio.dsdown.service.ManageLoginService;
import org.jadestudio.dsdown.util.SysInfo;
import org.jadestudio.dsdown.util.SysTools;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

@Component(value="/jadestudio/articleManage")
public class ArticleManageAction  extends DispatchAction {
	public ArticleManageAction(){}
	@Resource
	private ManageLoginService manageLoginService;
	@Resource
	private ArticleManageService articleManageService;

	/**
	 * 地址转向
	 * @param request
	 * @param mapping
	 * @param control 转向地址
	 * @param flag 是否检测  1带检测session / 0不带检测session
	 * @return
	 */
	private ActionForward gotoForward(HttpServletRequest request,ActionMapping mapping,String control,int flag){
		if(flag==1){
			int sessionFlag=manageLoginService.userSessionRecheck(request);
			if(sessionFlag==0){
			    ActionForward forward = new ActionForward("/jadestudio/portal.do");
				forward.setRedirect(true);
				return forward;
			}else{
				request.setAttribute("control",control);
				return mapping.findForward("gotoArticleManage");
			}
		}else{
			request.setAttribute("control",control);
			return mapping.findForward("gotoArticleManage");
		}
	}
	
	/**
	 * 引导至文章管理
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward gotoArticleList(ActionMapping mapping, ActionForm form,
	            HttpServletRequest request,
	            HttpServletResponse response) throws Exception{

		Map queryMap = SysTools.getParameterMap(request);
		queryMap.put("manageRecordsPerPage", SysInfo.manageRecordsPerPage);
		/*装载当前页数*/
		if(queryMap.get("CurrentPage")==null){
			queryMap.put("CurrentPage", "1");
			queryMap.put("CurrentPageInSql", 0);
		}else if(queryMap.get("CurrentPage").toString().equals("")){
			queryMap.put("CurrentPage", "1");
			queryMap.put("CurrentPageInSql", 0);
		}else{
			queryMap.put("CurrentPageInSql", (Integer.valueOf(queryMap.get("CurrentPage").toString())-1)*SysInfo.manageRecordsPerPage);
		}
		/*结果集*/
		List<Map> list = articleManageService.articleQueryByPaging(queryMap);
		request.setAttribute("list", list);
		/*装载总条数及总页数*/
		int maxRecords=articleManageService.articleCountQuery(queryMap);
		int maxPages=maxRecords%SysInfo.manageRecordsPerPage!=0?maxRecords/SysInfo.manageRecordsPerPage+1:maxRecords/SysInfo.manageRecordsPerPage;
		queryMap.put("MaxRecords", maxRecords);
		queryMap.put("MaxPages", maxPages);
		/*装载条件*/
		request.setAttribute("queryMap", queryMap);
		request.setAttribute("articleTypeMap", this.articleManageService.getArticleTypeList());
		return gotoForward(request,mapping,"gotoArticleList",1);
	}
	
	/**
	 * 引导到文章新增
	 */
	public ActionForward gotoArticleAdd(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		request.setAttribute("flag", "add");
		return gotoForward(request,mapping,"gotoArticleAddorModify",1);
	}
	
	
	/**
	 * 游戏模糊查询（返回json）
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	public void getGameByName(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		response.setContentType("text/html");   
        response.setCharacterEncoding("UTF-8"); 
		PrintWriter out = response.getWriter();   
		if(sessionFlag==0){
				out.write("[{\"id\":\"\",\"name\":\"SESSION丢失\"}]");   
		        out.flush();   
		        out.close(); 
		}else{
	        String requestString = request.getParameter("q");
	        requestString = new String(requestString.getBytes("iso8859-1"),"UTF-8");
	        List<Map> lt =this.articleManageService.gameQueryByName(requestString);
	        if(lt.size()>0){
		        //页面显示值   
		        String[] name=new String[lt.size()];
		        //实际值   
		        String[] id=new String[lt.size()];
		        for(int t=0;t<lt.size();t++){
		        	name[t]=lt.get(t).get("simplified_chinese_name")!=null?lt.get(t).get("simplified_chinese_name").toString():"";
		        	id[t]=lt.get(t).get("game_id")!=null?lt.get(t).get("game_id").toString():"";
		        }
		        StringBuffer sb = new StringBuffer("[");   
		        for(int i = 0;i < id.length;i++){   
		            sb.append("{\"id\":\"" + id[i] + "\",\"name\":\"" + name[i] +  "\"},");   
		        }   
		        sb.deleteCharAt(sb.lastIndexOf(",")).append("]");   
		        out.write(sb.toString());   
		        out.flush();   
		        out.close(); 
	        }else{
	        	out.write("[{\"id\":\"\",\"name\":\"不存在的数据\"}]");   
		        out.flush();   
		        out.close(); 
	        }
		}
	}
	
	/**
	 * 分割文章标题的关键字
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getArticleKeyWord(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		response.setContentType("text/html");   
        response.setCharacterEncoding("UTF-8"); 
		PrintWriter out = response.getWriter();
		if(sessionFlag==0){
			out.write("session丢失");
			out.flush();
		}else{
			String articleTitle=request.getParameter("articleTitle");
			if(articleTitle!=null && !articleTitle.equals("")){
				IKAnalyzer ka = new  IKAnalyzer(true);     
				Reader r = new StringReader(articleTitle);   
				TokenStream ts = (TokenStream)ka.tokenStream("title", r);   
				ts.addAttribute(TermAttribute.class);   
				String keyWords = "";
		        while (ts.incrementToken()) {   
		               TermAttribute ta =ts.getAttribute(TermAttribute.class);   
		               keyWords=keyWords+(ta.term()+SysInfo.keyWordSplit); 
		        }  
		        keyWords= keyWords.substring(0,keyWords.lastIndexOf("|"));
		        out.write(keyWords);
				out.flush();    
			}else{
				out.write("");
				out.flush();
			}
		}
		return null;
	}
	
	/**
	 * 文章新增逻辑
	 */
	public ActionForward articleAdd(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("utf-8");
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		if(sessionFlag==0){
		    ActionForward forward = new ActionForward("/jadestudio/portal.do");
			forward.setRedirect(true);
			return forward;
		}else{
			String article_name	 = request.getParameter("article_name")!=null?request.getParameter("article_name"):"";//	文章名称	
		    String article_type	 = request.getParameter("article_type")!=null?request.getParameter("article_type"):"";//	文章类型(1攻略 2资讯 3发售表 4推广)
			String article_tag		 = request.getParameter("article_tag")!=null?request.getParameter("article_tag"):"";//文章标签
			String article_writer	 = request.getParameter("article_writer")!=null?request.getParameter("article_writer"):"";//	作者
			String article_content	 = request.getParameter("article_content")!=null?request.getParameter("article_content"):"";//	文章内容	
			String article_isreship = request.getParameter("article_isreship")!=null?request.getParameter("article_isreship"):"";//	是否转载(1是 0否)
			String article_reship_url = request.getParameter("article_reship_url")!=null?request.getParameter("article_reship_url"):"";//	转载地址
			String article_is_redirect = request.getParameter("article_is_redirect")!=null?request.getParameter("article_is_redirect"):"";//	是否跳转
			String article_redirect_url = request.getParameter("article_redirect_url")!=null?request.getParameter("article_redirect_url"):"";//	跳转地址
			String article_position_top = request.getParameter("article_position_top")!=null?request.getParameter("article_position_top"):"";//	是否置顶
			String article_enable		 = request.getParameter("article_enable")!=null?request.getParameter("article_enable"):"";//文章是否开启
			String article_search_index = request.getParameter("article_search_index")!=null?request.getParameter("article_search_index"):""; //文章索引
			String article_keyword		 = request.getParameter("article_keyword")!=null?request.getParameter("article_keyword"):"";//文章关键字
			String article_description		 = request.getParameter("article_description")!=null?request.getParameter("article_description"):"";//文章描述
			String[] gameIds=(String[])request.getParameterValues("game_id_value")!=null?(String[])request.getParameterValues("game_id_value"):null;//关联游戏ID
			//int article_click = request.getParameter("article_click")!=null?Integer.valueOf(request.getParameter("article_click")):0;//文章点击数
			//String article_id  = request.getParameter("game_publish_url")!=null?request.getParameter("game_publish_url"):"";//文章ID
			ManageArticle manageArticle= new ManageArticle();
			manageArticle.setArticle_name(article_name);
			manageArticle.setArticle_type(article_type);
			manageArticle.setArticle_tag(article_tag);
			manageArticle.setArticle_writer(article_writer);
			manageArticle.setArticle_content(article_content);
			manageArticle.setArticle_isreship(article_isreship);
			manageArticle.setArticle_reship_url(article_reship_url);
			manageArticle.setArticle_is_redirect(article_is_redirect);
			manageArticle.setArticle_redirect_url(article_redirect_url);
			manageArticle.setArticle_position_top(article_position_top);
			manageArticle.setArticle_enable(article_enable);
			manageArticle.setArticle_search_index(article_search_index);
			manageArticle.setArticle_keyword(article_keyword);
			manageArticle.setArticle_description(article_description);
			//manageArticle.setArticle_click(article_click);
			
			String gameIdsValue="";
			if(gameIds!=null){
				for(int t=0;t<gameIds.length;t++){
					gameIdsValue+=(gameIds[t]+",");
				}
				gameIdsValue=gameIdsValue.substring(0,gameIdsValue.lastIndexOf(","));
			}
			manageArticle.setGame_ids(gameIdsValue);		
			String articleId=this.articleManageService.articleAdd(manageArticle);	
			ActionForward forward = new ActionForward("/jadestudio/articleManage.do?pm=gotoArticleList");
			forward.setRedirect(true);
			return forward;

		}
	}
	
	
	/**
	 * 文章删除逻辑
	 */
	public ActionForward articleDelete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		String articleId = (String)request.getParameter("id");
		if(sessionFlag==0){
		    ActionForward forward = new ActionForward("/jadestudio/portal.do");
			forward.setRedirect(true);
			return forward;
		}else{
			if(articleId!=null){
				int indexOfFlag = articleId.indexOf(",");
				if(indexOfFlag==-1){
					this.articleManageService.articleDeleteById(articleId);
				}else{
					String[] ids=articleId.split(",");
					for(int t=0;t<ids.length;t++){
						this.articleManageService.articleDeleteById(ids[t]);
					}
				}
			}
			ActionForward forward = new ActionForward("/jadestudio/articleManage.do?pm=gotoArticleList");
			forward.setRedirect(true);
			return forward;

		}
	}
	
	/**
	 * 引导到文章修改
	 */
	public ActionForward gotoArticleModify(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		if(sessionFlag==0){
		    ActionForward forward = new ActionForward("/jadestudio/portal.do");
			forward.setRedirect(true);
			return forward;
			
		}else{
			Map articleMap=articleManageService.articleQueryById(id);
			List<Map> gameArticleList = articleManageService.gameArticleQueryByArticleId(id);
			if(articleMap!=null){
				request.setAttribute("articleMap", articleMap);
				if(gameArticleList.size()>0){
					request.setAttribute("gameArticleList", gameArticleList);
				}
				
			}
		}
		request.setAttribute("flag", "modify");
		return gotoForward(request,mapping,"gotoArticleAddorModify",1);
	}
	
	/**
	 * 文章修改逻辑
	 */
	public ActionForward articleModify(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
		int sessionFlag=manageLoginService.userSessionRecheck(request);
		if(sessionFlag==0){
		    ActionForward forward = new ActionForward("/jadestudio/portal.do");
			forward.setRedirect(true);
			return forward;
		}else{
			String article_name	 = request.getParameter("article_name")!=null?request.getParameter("article_name"):"";//	文章名称	
		    String article_type	 = request.getParameter("article_type")!=null?request.getParameter("article_type"):"";//	文章类型(1攻略 2资讯 3发售表 4推广)
			String article_tag		 = request.getParameter("article_tag")!=null?request.getParameter("article_tag"):"";//文章标签
			String article_writer	 = request.getParameter("article_writer")!=null?request.getParameter("article_writer"):"";//	作者
			String article_content	 = request.getParameter("article_content")!=null?request.getParameter("article_content"):"";//	文章内容	
			String article_isreship = request.getParameter("article_isreship")!=null?request.getParameter("article_isreship"):"";//	是否转载(1是 0否)
			String article_reship_url = request.getParameter("article_reship_url")!=null?request.getParameter("article_reship_url"):"";//	转载地址
			String article_is_redirect = request.getParameter("article_is_redirect")!=null?request.getParameter("article_is_redirect"):"";//	是否跳转
			String article_redirect_url = request.getParameter("article_redirect_url")!=null?request.getParameter("article_redirect_url"):"";//	跳转地址
			String article_position_top = request.getParameter("article_position_top")!=null?request.getParameter("article_position_top"):"";//	是否置顶
			String article_enable		 = request.getParameter("article_enable")!=null?request.getParameter("article_enable"):"";//文章是否开启
			String article_search_index = request.getParameter("article_search_index")!=null?request.getParameter("article_search_index"):""; //文章索引
			String article_keyword		 = request.getParameter("article_keyword")!=null?request.getParameter("article_keyword"):"";//文章关键字
			String article_description		 = request.getParameter("article_description")!=null?request.getParameter("article_description"):"";//文章描述
			String[] gameIds=(String[])request.getParameterValues("game_id_value")!=null?(String[])request.getParameterValues("game_id_value"):null;//关联游戏ID
			int article_click = request.getParameter("article_click")!=null?Integer.valueOf(request.getParameter("article_click")):0;//文章点击数
			String article_id  = request.getParameter("article_id")!=null?request.getParameter("article_id"):"";//文章ID
			ManageArticle manageArticle= new ManageArticle();
			manageArticle.setArticle_name(article_name);
			manageArticle.setArticle_type(article_type);
			manageArticle.setArticle_tag(article_tag);
			manageArticle.setArticle_writer(article_writer);
			manageArticle.setArticle_content(article_content);
			manageArticle.setArticle_isreship(article_isreship);
			manageArticle.setArticle_reship_url(article_reship_url);
			manageArticle.setArticle_is_redirect(article_is_redirect);
			manageArticle.setArticle_redirect_url(article_redirect_url);
			manageArticle.setArticle_position_top(article_position_top);
			manageArticle.setArticle_enable(article_enable);
			manageArticle.setArticle_search_index(article_search_index);
			manageArticle.setArticle_keyword(article_keyword);
			manageArticle.setArticle_description(article_description);
			manageArticle.setArticle_click(article_click);
			manageArticle.setArticle_id(article_id);
			
			String gameIdsValue="";
			if(gameIds!=null){
				for(int t=0;t<gameIds.length;t++){
					gameIdsValue+=(gameIds[t]+",");
				}
				gameIdsValue=gameIdsValue.substring(0,gameIdsValue.lastIndexOf(","));
			}
			manageArticle.setGame_ids(gameIdsValue);		
			String articleId=this.articleManageService.articleModify(manageArticle);
			ActionForward forward = new ActionForward("/jadestudio/articleManage.do?pm=gotoArticleList");
			forward.setRedirect(true);
			return forward;
		}
	}
	
}
